<?php
defined('IN_IA') or exit('Access Denied');
require_once IA_ROOT . '/addons/xn_erp/inc/function.php';
global $_GPC, $_W;
$op = $_GPC['op'] ? "&op=" . $_GPC['op'] : '';
$url = $this->createWebUrl('goods') . $op;
$storage = DB('storage')->get_all();
//商品列表
if ($_GPC['op'] == 'list') {

    if ($_GPC['api'] == 'list') {
        $page = $_GPC['page'] ? $_GPC['page'] : 0;
        $limit = $_GPC['limit'] ? $_GPC['limit'] : 10;
        $goods = pdo_getslice('xn_erp_goods', array(), array($page, $limit), $count, array(), "", "id DESC");
        foreach ($goods as $key => $value) {
            $img_index = unserialize($value['img'])[0];
            if ($img_index) {
                $img_index = "../attachment/" . $img_index;
                $goods[$key]['img_index'] = "<a href='javascript:;' target='_blank' onMouseOver=\"toolTip('<img src=" . $img_index . ">')\" onMouseOut=\"toolTip()\">";
                $goods[$key]['img_index'] .= "<img src='" . $img_index . "'  align='absmiddle' class='tipimg'></a>";
            }

        }
        $goods_data = array("code" => 0, "msg" => "", "count" => $count, "data" => $goods);
        $goods_json = json_encode($goods_data);
        echo $goods_json;
        exit;
    }
    include $this->template('web/goods/goods_list');
}
// 商品添加
if ($_GPC['op'] == 'add') {
    $unit = DB("unit")->fetch_all();
    if ($_GPC['api'] == 'add') {
        $unit_name = DB("unit")->get_name_by_id($_GPC['unit_id']);
        $category_name = DB("category")->get_name_by_id($_GPC['category_id']);

        $goods_data = array(
            'name' => $_GPC['name'],
            'number' => $_GPC['number'],
            'sort' => $_GPC['sort'],
            'img' => serialize($_GPC['img']),
            'unit_id' => $_GPC['unit_id'],
            'unit_name' => $unit_name,
            'category_id' => $_GPC['category_id'],
            'category_name' => $category_name,
            'pur_price' => $_GPC['pur_price'],
            'sale_price' => $_GPC['sale_price'],
            'unit_cost' => $_GPC['unit_cost'],
            'remark' => $_GPC['remark'],
            'status' => $_GPC['status'] ? 1 : 0,
            'bar_code' => $_GPC['bar_code'],
            'disable' => 0,
            'delete' => 0,
            'addtime' => TIMESTAMP,
            'edittime' => TIMESTAMP,
        );

        $result = DB('goods')->insert($goods_data);
        if (!empty($result)) {
            echo "添加成功" . $unit_name;
        } else {
            echo "添加失败";
        }
        exit;
    }

    include $this->template('web/goods/goods_add');
}
// 商品数量
if ($_GPC['op'] == 'num') {

    if ($_GPC['api'] == 'list') {
        $sql = 'select  n.num,n.up,n.down,n.edittime , g.name,g.number,g.unit_name,g.category_name , s.sname from '
        . tablename('xn_erp_goods_num') . ' as n ' . ' left join '
        . tablename('xn_erp_goods') . ' as g on g.id  = n.gid' . ' left join '
        . tablename('xn_erp_storage') . ' as s on s.id = n.sid ';

        $goods_num = pdo_fetchall($sql);
        foreach ($goods_num as $key => $val) {
            $goods_num[$key]['edittime'] = date('Y-m-d H:i', $val['edittime']);
        }
        $goods_num_data = array("code" => 0, "msg" => "", "count" => $count, "data" => $goods_num);
        $goods_num_json = json_encode($goods_num_data);
        echo $goods_num_json;
        exit;
    }

    include $this->template('web/goods/goods_num');

}
// 入库操作
if ($_GPC['op'] == 'instorage') {
    $record_type = array(1 => "销售退货", 2 => "其他入库");
    if ($_GPC['api'] == 'list') {
        $page = $_GPC['page'] ? $_GPC['page'] : 0;
        $limit = $_GPC['limit'] ? $_GPC['limit'] : 10;
        $instorage = pdo_getslice('xn_erp_storage_record', array('type' => 1), array($page, $limit), $count, array(), "", "id DESC");
        foreach ($instorage as $key => $value) {
            $instorage[$key]['record_date'] = date('Y-m-d H:s:i', $value['record_date']);
            $instorage[$key]['record_type'] = $record_type[$value['record_type']];
        }
        $instorage_data = array("code" => 0, "msg" => "", "count" => $count, "data" => $instorage);
        $instorage_json = json_encode($instorage_data);
        echo $instorage_json;
        exit;
    }

    include $this->template('web/goods/goods_instorage');
}
// 入库详情
if ($_GPC['op'] == 'instorage_detail' && $_GPC['sid']) {
    $detail = DB('storage_record')->fetch_first_by_id($_GPC['sid']);
    $data = json_encode(unserialize($detail['goods_detail']));
    include $this->template('web/goods/goods_instorage_detail');
}
// 入库增加
if ($_GPC['op'] == 'instorage_add') {
    $rid = DB('storage_record')->get_id() + 1;

    $record = "IN-" . date("Ymd") . date("his") . sprintf("%04d", $rid);

    if ($_GPC['api'] == 'goods') {
        $page = $_GPC['page'] ? $_GPC['page'] : 1;
        $limit = $_GPC['limit'] ? $_GPC['limit'] : 5;
        $goods = pdo_getslice('xn_erp_goods', array(), array($page, $limit), $count, array('id', 'name', 'number', 'unit_name'), "", "id DESC");
        foreach ($goods as $key => $val) {
            $goods[$key]['snumber'] = 1;
        }
        $goods_data = array("code" => 0, "msg" => "", "count" => $count, "data" => $goods);
        $goods_json = json_encode($goods_data);
        echo $goods_json;
        exit;
    }

    if ($_GPC['api'] == 'add') {
        $goods = $_GPC['goods'];
        $sid = $_GPC['storage_id'];
        $storage_name = DB('storage')->get_name_by_id($sid);
        if (is_array($goods)) {

            DB('goods_num')->insert_by_goods($goods, $sid);

        } else {
            echo showmessage('添加失败，请先添加商品!', 'error');
            exit;
        }

        $arr = array(
            'record' => $_GPC['record'],
            'record_date' => strtotime($_GPC['record_date']),
            'storage_id' => $sid,
            'storage_name' => $storage_name,
            'record_type' => $_GPC['record_type'],
            'originator' => $_GPC['originator'],
            'remark' => $_GPC['remark'],
            'transactor' => $_GPC['transactor'],
            'type' => 1,
            'goods_detail' => serialize($goods),
            'datetime' => TIMESTAMP,
        );
        $result = DB('storage_record')->insert($arr);
        if (!empty($result)) {echo ('添加成功');}
        exit;
    }
    include $this->template('web/goods/goods_instorage_add');
}
// 出库操作
if ($_GPC['op'] == 'outstorage') {
    $record_type = array(1 => "销售出库", 2 => "其他出库");
    if ($_GPC['api'] == 'list') {
        $page = $_GPC['page'] ? $_GPC['page'] : 0;
        $limit = $_GPC['limit'] ? $_GPC['limit'] : 10;
        $instorage = pdo_getslice('xn_erp_storage_record', array('type' => 2), array($page, $limit), $count, array(), "", "id DESC");
        foreach ($instorage as $key => $value) {
            $instorage[$key]['record_date'] = date('Y-m-d', $value['record_date']);
            $instorage[$key]['record_type'] = $record_type[$value['record_type']];
        }
        $instorage_data = array("code" => 0, "msg" => "", "count" => $count, "data" => $instorage);

        $instorage_json = json_encode($instorage_data);
        echo $instorage_json;
        exit;
    }

    include $this->template('web/goods/goods_outstorage');

}
// 出库详情
if ($_GPC['op'] == 'outstorage_detail' && $_GPC['sid']) {
    $detail = DB('storage_record')->fetch_first_by_id($_GPC['sid']);
    $data = json_encode(unserialize($detail['goods_detail']));
    include $this->template('web/goods/goods_outstorage_detail');
}
// 出库增加
if ($_GPC['op'] == 'outstorage_add') {
    $rid = DB('transfer')->get_id() + 1;
    $record = "OUT-" . date("Ymd") . date("his") . sprintf("%04d", $rid);
    if ($_GPC['api'] == 'goods') {
        $page = $_GPC['page'] ? $_GPC['page'] : 1;
        $limit = $_GPC['limit'] ? $_GPC['limit'] : 5;
        $goods = pdo_getslice('xn_erp_goods', array(), array($page, $limit), $count, array('id', 'name', 'number', 'unit_name'), "", "id DESC");
        foreach ($goods as $key => $val) {
            $goods[$key]['snumber'] = 1;
        }
        $goods_json = xn_json($goods, $conut);
        echo $goods_json;
        exit;
    }
    if ($_GPC['api'] == 'add') {
        $goods = $_GPC['goods'];
        $sid = $_GPC['storage_id'];
        $storage_name = DB('storage')->get_name_by_id($sid);
        if (is_array($goods)) {
            //先判断仓库数量
            checkstorage($goods, $sid);

            foreach ($goods as $key => $val) {
                if ($val['snumber'] > 0) {
                    $gid = $val['id'];
                    $gnarr = DB('goods_num')->fetch_first(array('gid' => $gid, 'sid' => $sid));
                    $garr = array('gid' => $gid, 'sid' => $sid, 'num' => $val['snumber'], 'edittime' => TIMESTAMP);

                    if ($gnarr['id']) {

                        $garr['num'] = $gnarr['num'] - $val['snumber'];
                        DB('goods_num')->update_by_id($garr, $gnarr['id']);
                    } else {
                        DB('goods_num')->insert($garr);
                    }
                }
            }
        } else {
            echo showmessage('添加失败，请先添加商品!', 'error');
            exit;
        }

        $arr = array(
            'record' => $_GPC['record'],
            'record_date' => strtotime($_GPC['record_date']),
            'storage_id' => $sid,
            'storage_name' => $storage_name,
            'record_type' => $_GPC['record_type'],
            'originator' => $_GPC['originator'],
            'remark' => $_GPC['remark'],
            'transactor' => $_GPC['transactor'],
            'type' => 2,
            'goods_detail' => serialize($goods),
            'datetime' => TIMESTAMP,
        );
        $result = DB('transfer')->insert($arr);
        if (!empty($result)) {echo ('添加成功');}
        exit;
    }
    include $this->template('web/goods/goods_outstorage_add');
}
//库存调拨
if ($_GPC['op'] == 'transfer') {
    $state = array(1 => '<font color="red">在途</font>', 2 => '<font color="#009688">完成</font>');
    if ($_GPC['api'] == 'list') {
        $page = $_GPC['page'] ? $_GPC['page'] : 0;
        $limit = $_GPC['limit'] ? $_GPC['limit'] : 10;
        $transfer = pdo_getslice('xn_erp_transfer', array(), array($page, $limit), $count, array(), "", "id DESC");
        foreach ($transfer as $key => $value) {
            $transfer[$key]['outdate'] = date('Y-m-d h:i:s', $value['outdate']);
            if ($value['indate'] && $value['state'] == 2) {
                $transfer[$key]['indate'] = date('Y-m-d h:i:s', $value['indate']);
            } else {
                $transfer[$key]['indate'] = '';
            }
            $transfer[$key]['state'] = "<font color='#f00'>" . $state[$value['state']] . "</font>";
        }
        $transfer_data = array("code" => 0, "msg" => "", "count" => $count, "data" => $transfer);
        $transfer_json = json_encode($transfer_data);
        echo $transfer_json;
        exit;
    }
    include $this->template('web/goods/goods_transfer');
}
//库存调拨详情和入库
if ($_GPC['op'] == 'transfer_detail') {
    $detail = DB('transfer')->fetch_first_by_id($_GPC['tid']);
    $detail['outdate'] = date('Y-m-d h:i:s', $detail['outdate']);
    $detail['indate'] = date('Y-m-d h:i:s', $detail['indate']);

    $state = array(1 => '<font color="red">在途</font>', 2 => '<font color="#009688">完成</font>');
    $goods = unserialize($detail['goods_detail']);

    $data = json_encode($goods);

    if ($_GPC['api'] == 'in' && $_GPC['tid']) {

        in_storage_by_goods($goods, $detail['instorageid']);

        $arr = array(
            'indate' => strtotime($_GPC['indate']),
            'state' => 2,
        );
        $result = DB('transfer')->update_by_id($arr,$_GPC['tid']);
        if (!empty($result)) {
            echo xn_json(array(), 0, showmessage('入库成功'), 0);
        }
        exit;
    }

    include $this->template('web/goods/goods_transfer_detail');
}
//库存调拨增加
if ($_GPC['op'] == 'transfer_add') {
    $rid = DB('transfer')->get_id() + 1;
    $record = "DB-" . date("Ymd") . date("his") . sprintf("%04d", $rid);

    if ($_GPC['api'] == 'goods' && $_GPC['sid']) {
        $page = $_GPC['page'] ? $_GPC['page'] : 1;
        $limit = $_GPC['limit'] ? $_GPC['limit'] : 5;
        $startRow = ($page - 1) * $limit;

        $sql = 'select  n.num,n.up,n.down ,g.id, g.name,g.number,g.unit_name,g.category_name , s.sname from '
        . tablename('xn_erp_goods_num') . ' as n ' . ' left join '
        . tablename('xn_erp_goods') . ' as g on g.id  = n.gid' . ' left join '
        . tablename('xn_erp_storage') . ' as s on s.id = n.sid WHERE 1 AND s.id = ' . $_GPC['sid'] . ' ORDER by g.id DESC LIMIT ' . $startRow . ',' . $limit;
        $goods = pdo_fetchall($sql);
        $count = DB('goods_num')->count(array('sid' => $_GPC['sid']));
        foreach ($goods as $key => $val) {
            $goods[$key]['snumber'] = 1;
        }
        $goods_json = xn_json($goods, $conut);
        echo $goods_json;
        exit;
    }

    if ($_GPC['api'] == 'add') {
        $goods = $_GPC['goods'];
        $outid = $_GPC['outstorageid'];
        $inid = $_GPC['instorageid'];
        $outstorage_name = DB('storage')->get_name_by_id($outid);
        $instorage_name = DB('storage')->get_name_by_id($inid);
        if (is_array($goods)) {
            //先判断仓库数量

            $r = checkstorage($goods, $outid);
            if ($r['code'] == -1) {echo ejson_encode($r);exit;}

            foreach ($goods as $key => $val) {
                $gid = $val['id'];
                $out_gnarr = DB('goods_num')->fetch_first(array('gid' => $gid, 'sid' => $outid)); //出库仓库的商品数量
                $garr = array('gid' => $gid, 'sid' => $outid, 'num' => $val['snumber'], 'edittime' => TIMESTAMP);
                $garr['num'] = $out_gnarr['num'] - $val['snumber'];
                DB('goods_num')->update_by_id($garr, $out_gnarr['id']);
            }

        } else {
            echo xn_json(array(), 0, showmessage('添加失败，请先添加商品!', 'error'), -1);
            exit;
        }

        $arr = array(
            'record' => $_GPC['record'],
            'outstorage' => $outstorage_name,
            'outstorageid' => $outid,
            'instorage' => $instorage_name,
            'instorageid' => $inid,
            'outdate' => strtotime($_GPC['outdate']),
            'originator' => $_GPC['originator'],
            'transactor' => $_GPC['transactor'],
            'state' => 1,
            'remark' => $_GPC['remark'],
            'goods_detail' => serialize($goods),
            'outdatetime' => TIMESTAMP,
        );
        $result = DB('transfer')->insert($arr);
        if (!empty($result)) {
            echo xn_json(array(), 0, showmessage('添加成功'), 0);
        }
        exit;
    }

    include $this->template('web/goods/goods_transfer_add');
}
